import { CodecBase } from "./codec_type";

export class ByteView implements CodecBase {

    buf: number[] | Uint8Array;
    index: number;
    len: number;

    constructor(buf: number[] | Uint8Array, index: number, len: number) {
        this.buf = buf;
        this.index = index;
        this.len = len;
    }

    encode(buf: number[], index: number): void {
        buf[index] = this.len;
        for (let i = 0; i < this.len; i ++) {
            buf[index + 1 + i] = this.buf[this.index + i];
        }
    }
    decode(buf: number[], index: number): void {
        this.buf = buf;
        this.index = index + 1;
        this.len = buf[index];
    }
    size(): number {
        return 1 + this.len;
    }

    toString(): string {
        const decoder = new TextDecoder('utf-8');
        const bytes = new Uint8Array(this.len);
        for (let i = 0; i < this.len; i ++) {
            bytes[i] = this.buf[this.index + i];
        }
        return decoder.decode(bytes);
    }
}
